﻿<?php
namespace YDCMS\controllers;

class BaseController
{
    /**
     * @var array 视图数据
     */
    protected $viewData = [];

    /**
     * 渲染视图
     * @param string $view 视图名称
     * @param array $data 视图数据
     */
    protected function render($view, $data = [])
    {
        $this->viewData = array_merge($this->viewData, $data);
        
        $viewFile = APP_PATH . 'views/' . $view . '.php';
        
        if (!file_exists($viewFile)) {
            throw new \Exception('View file not found: ' . $view);
        }
        
        extract($this->viewData);
        
        ob_start();
        require $viewFile;
        $content = ob_get_clean();
        
        echo $content;
    }

    /**
     * 返回JSON响应
     * @param mixed $data 响应数据
     * @param int $status HTTP状态码
     */
    protected function json($data, $status = 200)
    {
        header('Content-Type: application/json');
        http_response_code($status);
        echo json_encode($data);
    }

    /**
     * 重定向
     * @param string $url 重定向URL
     * @param int $status HTTP状态码
     */
    protected function redirect($url, $status = 302)
    {
        header('Location: ' . $url, true, $status);
        exit;
    }
}
